# -*- coding: utf-8 -*-
#===================================================
# @Time : 2021/3/25 17:09                           
# @Author : weni09                                  
# @File : api.py
#===================================================

from fastapi import APIRouter,Depends
from fastapi.requests import Request
from starlette.datastructures import UploadFile
from tortoise.contrib.pydantic import pydantic_queryset_creator
from admin.fastapi_admin.schemas import BulkIn
from .fastapi_admin.depends import get_model,jwt_required
from starlette.templating import Jinja2Templates
from datetime import datetime
from setting import IMAGE_PATH,BASE_DIR,IMAGE_SIZE,IMAGE_COUNT
import os,random




router = APIRouter()


templates = Jinja2Templates(directory="admin/templates")

@router.post("/rest/{resource}/bulk/test_bulk")
async def test_bulk(bulk_in: BulkIn, model=Depends(get_model)):
    qs = model.filter(pk__in=bulk_in.pk_list)
    pydantic = pydantic_queryset_creator(model)
    ret = await pydantic.from_queryset(qs)
    return ret.dict()

@router.get("/home",dependencies=[Depends(jwt_required)])
async def home():
    return {"html": templates.get_template("home.html").render()}




# def gen_rnd_filename():
#     """
#     :return: 随机文件名前缀--年月日时分秒+4位随机数
#     """
#     filename_prefix = datetime.now().strftime('%Y%m%d%H%M%S')
#     return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))
#

# @router.post("/upload-img",dependencies=[Depends(jwt_required)])
# async def recv_file(*,request:Request):
#     data = []
#     response_msg = {
#         "errno": 0,
#          "data": data
#     }
#
#     form_data = await request.form()
#
#     files = [file for file in form_data.values() if isinstance(file, UploadFile)]
#
#     if not files:
#         response_msg["errno"] = 'NO_IMG'
#         return response_msg
#     if len(files) > IMAGE_COUNT:
#         response_msg["errno"] = 'IMG_COUNT_OVER'
#         return response_msg
#
#     file_dir = os.path.join(IMAGE_PATH,str(datetime.now().year),str(datetime.now().strftime("%m")),str(datetime.now().strftime("%d")))
#     file_abs_dir = os.path.join(BASE_DIR,file_dir)
#     if not os.path.exists(file_abs_dir):
#         try:
#             os.makedirs(file_abs_dir)
#         except Exception:
#             response_msg["errno"] = 'ERROR_CREATE_DIR'
#             return response_msg
#
#     # url 主要地址,静态文件服务地址
#     url_domain = request.base_url.__str__()
#     url_domain += '/' if url_domain[-1] != '/' else ''
#
#     for file in files:
#         file_data = file.file.read()
#         if len(file_data) > IMAGE_SIZE:
#             response_msg["errno"] = 'IMAGE_OVER_LARGE'
#             return response_msg
#         prefix = f"{gen_rnd_filename()}_" # 前缀
#         filepath = os.path.join(file_abs_dir,prefix + file.filename) # 文件绝对路径
#         # 批量文件写入
#         try:
#             with open(filepath,'wb') as f:
#                 f.write(file_data)
#             url = url_domain + file_dir.replace('\\','/') + "/" + prefix + file.filename
#             alt = prefix + file.filename
#             data.append(dict(url=url,alt=alt))
#         # except Exception as e:
#             # error = str(e)
#             # pass
#         finally:
#             file.file.close()
#             f.close()
#     if len(data) == 0:
#         response_msg["errno"] = 'WRITE_ALL_FAILED'
#     if data and len(data) < len(files):
#         response_msg["errno"] = 'WRITE_SCOPE_FAILED'
#     return response_msg

import jwt
from .fastapi_admin.factory import app
from fastapi.exceptions import HTTPException
from starlette.status import HTTP_401_UNAUTHORIZED
from .token import token

@router.post("/token/refresh")
async def refresh_token(re_token:dict):
    """
    :param re_token: 带refresh_token的json
    :return: 刷新过期后时间的授权信息
    """
    credentials_exception = HTTPException(HTTP_401_UNAUTHORIZED)
    try:
        payload = jwt.decode(re_token.get('refresh_token'),app.admin_secret,algorithms=["HS256","HS512"])
        user_id = payload.get("user_id")
        if user_id is None:
            raise credentials_exception
    except jwt.PyJWTError:
        raise credentials_exception

    success_authenticate = {"user":payload["user"],"user_id":payload["user_id"]}
    access_token,refresh_token = token.create_access_token(success_authenticate)
    success_authenticate.update(token=access_token,refresh_token=refresh_token)
    return success_authenticate